package com.example.java.base.rabbitmq.util;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * RabbitMqUtil:
 *
 * @author zhangxiaoxiang
 * @date 2020/11/15
 */
public class RabbitMqUtil {
    public static ConnectionFactory connectionFactory;

    static {
        //只执行一次
        connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("47.108.168.46");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("ems");
        connectionFactory.setUsername("ems");
        connectionFactory.setPassword("ems");
    }

    /**
     * 连接对象的方法
     *
     * @return Connection
     */
    public static Connection getConnection() {
        try {
            return connectionFactory.newConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 关闭通道和关闭连接工具方法
     *
     * @param channel    通道
     * @param connection 连接
     */
    public static void closeConnectionAndChanel(Channel channel, Connection connection) {
        try {
            if (channel != null) {
                channel.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        }
    }
}
